/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  TreeLinkNode *left, *right, *next;
 *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 * };
 */
class Solution {
public:
    void connect(TreeLinkNode *root) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (root == NULL) {
            return;
        }
        while (root && root->left && root->right) {
            TreeLinkNode *t = root->left;
            TreeLinkNode *cur = root;
            while (cur && cur->left) {
                cur->left->next = cur->right;
                cur->right->next = (cur->next ? cur->next->left : NULL);
                cur = cur->next;
            }
            root = t;
        }
    }
};
